#!/bin/python
# -*- coding:utf-8 -*-
import re
import sys
try:
    dicFilePath=sys.argv[1]
    tmptFilePath=sys.argv[2]
    destFilePath=sys.argv[3]
    # 读取字典文件
    dicFile = open(dicFilePath, mode="r")
    # 读取模板文件
    tmptFile = open(tmptFilePath, mode="r")
except BaseException:
    print "[Error]  Wrong file path passed in !"
    print "[Error]  End of replacement process !"
    exit()

# 读取时以行为单位
dicListStr=dicFile.readlines()
dicFile.close()
# 初始哈配置字典数组
confDic = []
# 分析配置文件的每一行，去掉多余字符后，添加到数组
for item in dicListStr:
    item = item.strip('\n\r')
    if len(item.strip()) == 0 or item.strip()[0] == "#":
      continue
    item = item.replace(' ','')
    item = item.split("=")
    confDic.append(item)
# 将长度为2的数组转换成字典
confDic = dict(confDic)

# 将模板文件整个读取出来
tmptFileStr=tmptFile.read()
tmptFile.close()
# 按照规则匹配出需要替换的字符串
reIter = re.finditer('\{\{[_a-zA-Z0-9]+\}\}',tmptFileStr)
# 挨个检测，是否可被替换
for item in reIter:
    dicName = item.group().strip('{}')
    # 判断配置文件中是否有此配置
    if confDic.has_key(dicName):
        tmptFileStr = re.sub('{{'+dicName+'}}',confDic[dicName],tmptFileStr)
    else:
        print "[Error]  '"+dicName+"' replace failed!"


try:
    # 将替换完变量的模板字符串放入目标文件中
    destFile = open(destFilePath, mode="w+")
except BaseException:
    print "[Error]  Wrong file path passed in !"
    print "[Error]  End of replacement process !"
    exit()

destFile.write(tmptFileStr)
destFile.flush()
# 关闭文件
destFile.close()